/**
 * 收到请求时，把网页响应上去
 * http://localhost:8081/
 * 将index.html相应到前端
 */

const http = require("http")
const https = require("https");
const url = require("url")
const fs = require("fs")
const path = require("path")
const cheerio = require("cheerio")

var reqUrl = "https://maoyan.com/films";
var movieList = [];
const { readdir } = require("fs/promises")

http.createServer((req,res)=>{
    var urlObj = url.parse(req.url)
    // console.log(urlObj);
    var pathname = urlObj.pathname;
    if(pathname == "/"){
        var filePath = path.join(__dirname,"/index.html")
        //同步的读取结果在回调函数里面，异步的读取结果可以直接提取
        fs.readFile(filePath,(err,data)=>{
            if(err){
                console.log(err)
            }else{
                res.writeHead(200,{"Content-Type":"text/html;charset=utf8"});
                res.write(data)
                res.end();
            }

        })
        //get只能拉取数据，而post还可以传递数据
    }else if(pathname == "/getlist"){
        https.get(reqUrl,(resObj)=>{
            var htmlStr = "";
            resObj.on("data",(chunk)=>{
                htmlStr += chunk;
            })
            resObj.on("end",()=>{
                var $ = cheerio.load(htmlStr)
                $(".movie-item-title a").each((i,el)=>{
                    var movieTitle = $(el).text()
                    var movieId = $(el).attr("data-val");
                    movieId = movieId.slice(movieId.indexOf(":")+1,-1)
                    var num1 = $(el).parent().next().children(".integer").text();
                    var num2 = $(el).parent().next().children(".fraction").text();
                    var rate = num1+num2
                    var movieObj = {movieId:movieId,movieName:movieTitle,movieRate:rate}
                    movieList.push(movieObj);
                })

                res.writeHead(200,{"Content-Type":"text/plain"});
                res.write(JSON.stringify(movieList));
                res.end()
            })
        })
    }
}).listen(8081)